#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/5 14:31
# @Author : luhongxuan
# @Site :
# @File : auth.py
# @Software: PyCharm

import pandas as pd
import numpy as np
from converter import Converter


def get_meta_data(file_path):
    meta_filed_names = ['label_name', 'field_name', 'type']
    sheet_name = 'meta'
    skiprows = 0
    meta_data_dtf = pd.read_excel(file_path, sheet_name=sheet_name, names=meta_filed_names, skiprows=skiprows)

    data = meta_data_dtf.to_dict(orient='records')

    return data


def data_cell_2_value(value, type_in_str):
    if value is None:
        return None
    if value == 'NaT':
        return None
    if type_in_str == 'str':
        if value:
            return str(value)
        return None
    if type_in_str == 'int':
        if np.isnan(value):
            return None
        return int(value)

    if type_in_str == 'float':
        if np.isnan(value):
            return None
        return float(value)
    if type_in_str == 'date':
        return value.strftime('%Y-%m-%d')
    if type_in_str == 'datetime':
        return value.strftime('%Y-%m-%d %H:%M')
    if type_in_str == 'bool':
        return Converter.convert_to_boolean(value)
    return '不识别的值类型，目前只支持字符串、整数、浮点数'


def file_2_data(file_path, sheet_name='Sheet1', skiprows=0):
    datetime_dtype_args = {}
    meta_data = get_meta_data(file_path)
    for i in meta_data:
        type_in_str = i.get('type', 'str')
        if type_in_str == 'datetime':
            datetime_dtype_args[i['label_name']] = np.datetime64
    if datetime_dtype_args:
        raw_data = pd.read_excel(file_path, sheet_name=sheet_name, skiprows=skiprows, dtype=datetime_dtype_args)
    else:
        raw_data = pd.read_excel(file_path, sheet_name=sheet_name, skiprows=skiprows)

    data_before_filter = raw_data.to_dict(orient='records')
    data = []
    for i in data_before_filter:
        data_item = {}
        for meta in meta_data:
            try:
                meta_type = meta.get('type', 'str')
                value = data_cell_2_value(i.get(meta['label_name']), meta_type)
                key = meta['field_name']
                data_item[key] = value
            except:
                import traceback
                traceback.print_exc()
        data.append(data_item)

    # 返回前端时删除用户未填字段
    for item_dict in data:
        del_keys = []
        for item_key, item_value in item_dict.items():
            if item_value == 'nan':
                del_keys.append(item_key)
        for del_key in del_keys:
            del item_dict[del_key]

    return data
